package org.company.management.ui;

import org.company.management.controller.EmployeeGroupJpaController;
import org.company.management.controller.UiController;
import org.company.management.controller.exceptions.NonexistentEntityException;
import org.company.management.entity.EmployeeGroup;
import org.company.management.utilities.CustomMessageBox;
import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.wb.swt.layout.grouplayout.GroupLayout;
import org.eclipse.wb.swt.layout.grouplayout.LayoutStyle;

/**
 * @author Paner
 *
 */
public class GroupEditor extends EditorPart implements SelectionListener {

	public final static String ID = Strings.groupEditorId;
	
	private Button _addButton;
	private Button _removeButton;
	private Button _updateButton;
	private Table table;
	private TableViewer _tableViewer;
	private int _row = 1;
	
	/* 
	 * Constructor, sets editor`s image
	 */
	public GroupEditor() {
		setTitleImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.addGroupPicture16x16));
		// TODO Auto-generated constructor stub
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);

	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void createPartControl(Composite parent) {
		createControls(parent);
		createColumns(parent);
		createLayout(parent);
		fillTable();

	}
	
	/*
	 * Creates widgets
	 */
	private void createControls(Composite parent) 
	{
		_tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
		table = _tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setBackground(SWTResourceManager.getColor(SWT.COLOR_LIST_BACKGROUND));
		
		_addButton = new Button(parent, SWT.NONE);
		_addButton.setToolTipText(Strings.addGroupTooltip);
		_addButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.addGroupPicture32x32));
		_addButton.addSelectionListener(this);
		
		_updateButton = new Button(parent, SWT.NONE);
		_updateButton.setToolTipText(Strings.editGroupTooltip);
		_updateButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.editGroupPicture32x32));
		_updateButton.addSelectionListener(this);
		
		_removeButton = new Button(parent, SWT.NONE);
		_removeButton.setToolTipText(Strings.deleteGroupTooltip);
		_removeButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.deleteGroupPicture32x32));
		_removeButton.addSelectionListener(this);
		
	}

	/*
	 * Creates layout
	 */
	private void createLayout(Composite parent) {
		GroupLayout gl_parent = new GroupLayout(parent);
		gl_parent.setHorizontalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(gl_parent.createParallelGroup(GroupLayout.LEADING)
						.add(table, GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
						.add(gl_parent.createSequentialGroup()
							.add(_addButton)
							.addPreferredGap(LayoutStyle.RELATED)
							.add(_updateButton)
							.addPreferredGap(LayoutStyle.RELATED)
							.add(_removeButton)))
					.addContainerGap())
		);
		gl_parent.setVerticalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(gl_parent.createParallelGroup(GroupLayout.BASELINE)
						.add(_addButton)
						.add(_updateButton)
						.add(_removeButton))
					.addPreferredGap(LayoutStyle.RELATED)
					.add(table, GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
					.addContainerGap())
		);
		parent.setLayout(gl_parent);
		
	}
	
	/*
	 * Fills the components of the editor
	 */
	private void fillTable()
	{
		//copy groups from db
		EmployeeGroupJpaController employeeGroupDao = new EmployeeGroupJpaController();
		_tableViewer.setContentProvider(new ArrayContentProvider());
		_tableViewer.setInput(employeeGroupDao.findEmployeeGroupEntities());
	}
	
	/*
	 * Creates the columns for group data
	 */
	private void createColumns(final Composite parent) {
		String[] titles = { Strings.serialNumber, Strings.name, Strings.lastName, Strings.phone, Strings.group, Strings.euroPerHour };
		int[] bounds = { 100, 100, 100, 100, 100 };

		// First column is for the first name
		TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				return Integer.toString(_row++);
			}
		});

		// Second column is for the last name
		col = createTableViewerColumn(titles[1], bounds[1], 1);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				EmployeeGroup p = (EmployeeGroup) element;
				return p.getName();
			}
		});
		
		// third column is for payment
		col = createTableViewerColumn(titles[5], bounds[2], 2);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				EmployeeGroup p = (EmployeeGroup) element;
				String s = Float.toString(p.getHourlyrateofpayment());
				return s;
			}
		});
		
	}
	
	/*
	 * Enable column editing 
	 */
	private TableViewerColumn createTableViewerColumn(String title, int bound, final int colNumber) 
	{
		//Set table column properties
		final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer,SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(title);
		column.setWidth(bound);
		column.setResizable(true);
		column.setMoveable(true);
		return viewerColumn;
	}

	@Override
	public void widgetSelected(SelectionEvent e) {
		Object selectedWidget = e.getSource();
		if (selectedWidget == _addButton)
		{
			UiController.showEditor(Strings.groups, AddGroupEditor.ID);
		}
		else if (selectedWidget == _removeButton)
		{
			try
			{
				TableItem[] selectedEmployeeGroup = _tableViewer.getTable().getSelection();
				int selectedItemsCount = selectedEmployeeGroup.length;
				
				if(selectedItemsCount != 0)
				{
					if(CustomMessageBox.showYesNoMessageBox(Strings.invalidInputHeader, Strings.confirmSelection))
					{
						//delete group from db
						EmployeeGroup employeeGroup = (EmployeeGroup)selectedEmployeeGroup[0].getData();
						EmployeeGroupJpaController employeeGroupDao = new EmployeeGroupJpaController();
						employeeGroupDao.destroy(employeeGroup.getId());
						_tableViewer.remove(employeeGroup);
					}
				}
			} 
			catch (NonexistentEntityException ex)
			{
					ex.printStackTrace();
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		else if (selectedWidget == _updateButton)
		{
			try
			{
				TableItem[] selectedEmployeeGroup = _tableViewer.getTable().getSelection();
				EmployeeGroup employeeGroup = (EmployeeGroup)selectedEmployeeGroup[0].getData();
				UiController.showEditor(employeeGroup, UpdateEmployeeGroupEditor.ID);
			}
			catch(Exception ex)
			{
				//
			}
		}
	}
	
	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}
	
}
